package org.btik.lightdev.dev.tcp;

import org.btik.light.meta.ByteReader;
import org.btik.light.meta.Dev;
import org.btik.light.meta.base.Command;
import org.btik.light.meta.base.Report;
import org.btik.light.meta.exception.LightException;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class BioDev implements Dev {
    private final Socket socket;
    private final OutputStream outputStream;

    public BioDev(Socket client) throws IOException {
        this.socket = client;
        this.outputStream = client.getOutputStream();
    }

    @Override
    public long getTimeOut() {
        return 0;
    }

    @Override
    public void sendCmdOrMsg(Command msg) {
        try {
            outputStream.write(msg.encode());
            outputStream.flush();
        } catch (IOException e) {
            if (!isOnline() || "Connection reset by peer".equals(e.getMessage())) {
                throw new LightException("dev disconnected");
            }
            throw new LightException(e);
        }
    }

    @Override
    public Report sendSyncCmd(Command cmd, long timeout) {
        return null;
    }

    @Override
    public boolean isOnline() {
        return !socket.isClosed() && socket.isConnected();
    }
}
